package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"net/http"
	"os"
)

var (
	DB *gorm.DB
)

func main() {
	r := gin.Default()
	DB = InitDB()
	r.GET("/GetManageList", func(c *gin.Context) {
		//var query User
		//if err := c.ShouldBindJSON(&query); err != nil {
		//	c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		//	return
		//}
		db := DB.Model(&User{})
		var dataList []User
		//db.Find(&dataList,"state = ?",query.State)
		db.Preload("Info").Find(&dataList)

		//Success(dataList)
		c.JSON(200, gin.H{
			"data": dataList,
		})
	})
	r.GET("/GetManage", func(c *gin.Context) {
		var query User
		if err := c.ShouldBindQuery(&query); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		db := DB.Model(&User{})
		var user User
		//db.Find(&dataList,"state = ?",query.State)
		db.Where("id", query.ID).Preload("Info", "user_id = ?", query.ID).Find(&user)

		//Success(dataList)
		c.JSON(200, gin.H{
			"data": user,
		})
	})
	//r.GET("/get", func(c *gin.Context) {
	//	var query User
	//	c.ShouldBindQuery(&query)
	//	//id := c.QueryParam("id")
	//	c.JSON(200, gin.H{
	//		"data": query,
	//	})
	//})
	r.POST("/AddManage", func(c *gin.Context) {
		var user User
		if err := c.ShouldBindJSON(&user); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		DB.Create(&user)
		c.JSON(200, gin.H{
			"msg": "添加成功",
		})
	})
	r.Run(":8081") // 监听并在 0.0.0.0:8080 上启动服务
}
func InitDB() *gorm.DB {
	HomeDir, _ := os.Getwd()
	database, err := gorm.Open(sqlite.Open(HomeDir+"/store.db"), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		fmt.Print("initDB err:", err)
	}
	database.AutoMigrate(&User{}, &Info{})
	return database
}

// models
type User struct {
	ID   uint   `json:"id" form:"id" gorm:"primarykey"`
	Name string `json:"name" form:"name" gorm:"column:name;comment:名字"`
	Info []Info `json:"info" form:"info"`
}

func (User) TableName() string {
	return "user"
}

type Info struct {
	ID     uint `json:"id" gorm:"primarykey"`
	Age    uint `json:"age" gorm:"column:age"`
	UserId uint `json:"user_id" gorm:"column:user_id;comment:关联标记"`
}

func (Info) TableName() string {
	return "info"
}

// res
type Resp struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// Success ...
func Success(data interface{}) *Resp {
	return &Resp{
		Code: 0,
		Data: data,
	}
}

// Fail ...
func Fail(message string) *Resp {
	return &Resp{
		Code: -1,
		Msg:  message,
	}
}
